const isMobile = /mobile/i.test(window.navigator.userAgent)

const Util = {
    secondToTime: (second) => {
        second = second || 0
        if (second === 0 || second === Infinity || second.toString() === 'NaN') {
            return '00:00'
        }
        const add0 = (num) => (num < 10 ? '0' + num : '' + num)
        const hour = Math.floor(second / 3600)
        const min = Math.floor((second - hour * 3600) / 60)
        const sec = Math.floor(second - hour * 3600 - min * 60)
        return (hour > 0 ? [hour, min, sec] : [min, sec]).map(add0).join(':')
    },

    getElementViewLeft: (element) => {
        let actualLeft = element.offsetLeft
        let current = element.offsetParent
        while (current !== null) {
            actualLeft += current.offsetLeft
            current = current.offsetParent
        }
        return actualLeft - document.documentElement.scrollLeft
    },

    getElementViewTop: (element) => {
        let actualTop = element.offsetTop
        let current = element.offsetParent
        while (current !== null) {
            actualTop += current.offsetTop
            current = current.offsetParent
        }
        let elementScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        return actualTop - elementScrollTop
    },

    getBoundingClientRectViewLeft(element) {
        const scrollTop = window.scrollY || window.pageYOffset ||
            document.body.scrollTop + ((document.documentElement && document.documentElement.scrollTop) || 0)
        if (element.getBoundingClientRect) {
            if (typeof this.getBoundingClientRectViewLeft.offset !== 'number') {
                let temp = document.createElement('div')
                temp.style.cssText = 'position:absolute;top:0;left:0;'
                document.body.appendChild(temp)
                this.getBoundingClientRectViewLeft.offset = -temp.getBoundingClientRect().top - scrollTop
                document.body.removeChild(temp)
                temp = null
            }
            const rect = element.getBoundingClientRect()
            const offset = this.getBoundingClientRectViewLeft.offset

            return rect.left + offset
        } else {
            return this.getElementViewLeft(element)
        }
    },

    isMobile: isMobile,

    isFirefox: /firefox/i.test(window.navigator.userAgent),

    isChrome: /chrome/i.test(window.navigator.userAgent),

    isSafari: /safari/i.test(window.navigator.userAgent),

    event: {
        down: isMobile ? 'touchstart' : 'mousedown',
        move: isMobile ? 'touchmove' : 'mousemove',
        up: isMobile ? 'touchend' : 'mouseup',
        click: 'click',
        enter: 'mouseenter',
        leave: 'mouseleave',
    },
};

export default Util
